package com.yh.diary_dao;

import android.app.ListActivity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.MenuCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.SearchView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import com.afa.tourism.greendao.gen.DaoMaster;
import com.afa.tourism.greendao.gen.DaoSession;
import com.afa.tourism.greendao.gen.DiaryDao;
import com.afa.tourism.greendao.gen.DaoMaster.DevOpenHelper;
import com.yh.diary_dao.swipemenulistview.SwipeMenu;
import com.yh.diary_dao.swipemenulistview.SwipeMenuCreator;
import com.yh.diary_dao.swipemenulistview.SwipeMenuItem;
import com.yh.diary_dao.swipemenulistview.SwipeMenuListView;

public class MainActivity extends AppCompatActivity {
    private Button New_btn;

    private SQLiteDatabase db;
    private DaoMaster daoMaster;
    private DaoSession daoSession;
    private DiaryDao diaryDao;
    private Cursor cursor;
    private SwipeMenuListView listView;
    private Diary diary;
    private SearchView search;
    private SimpleCursorAdapter adapter;
    private Cursor cursor1;
    int flag=1;
    String search_comfirm="false";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.diary_list);
        listView=(SwipeMenuListView) findViewById(R.id.list);

        //初始化GreenDao和ListView
        InitDAO();
        InitList();

        New_btn = (Button) findViewById(R.id.New);
        New_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent0 = new Intent(MainActivity.this, DiaryEditor.class);
                intent0.setAction(DiaryEditor.INSERT_DIARY_ACTION);
                intent0.setData(getIntent().getData());
                startActivity(intent0);
                overridePendingTransition(R.anim.anmi_in,R.anim.anim_out);
                MainActivity.this.finish();
                overridePendingTransition(R.anim.anmi_in,R.anim.anim_out);
                cursor.requery();
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String mid = Long.toString(id);
                Intent intent = new Intent(MainActivity.this, DiaryEditor.class);
                intent.setAction(DiaryEditor.EDIT_DIARY_ACTION);
                Bundle bundle = new Bundle();
                bundle.putLong("id", id);
                intent.putExtras(bundle);
                startActivity(intent);
                overridePendingTransition(R.anim.anmi_in,R.anim.anim_out);
                MainActivity.this.finish();
                overridePendingTransition(R.anim.anmi_in,R.anim.anim_out);
                cursor.requery();
            }
        });
        //侧滑删除，按钮创建
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                //添加分享按钮
                SwipeMenuItem item2 = new SwipeMenuItem(getApplicationContext());
                item2.setWidth(200);
                item2.setIcon(R.drawable.share);
                menu.addMenuItem(item2);
                //添加删除按钮
                SwipeMenuItem item = new SwipeMenuItem(getApplicationContext());
                item.setWidth(200);
                item.setIcon(R.drawable.delete);
                menu.addMenuItem(item);
            }
        };
        //侧滑后按钮的监听事件
        listView.setMenuCreator(creator);
        listView.setSwipeDirection(SwipeMenuListView.DIRECTION_LEFT);
        listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                        cursor.moveToPosition(position);
                        //id=cursor.getLong(cursor.getColumnIndex(DiaryDao.Properties.Id.columnName));
                        String title=cursor.getString(cursor.getColumnIndex(DiaryDao.Properties.Title.columnName));
                        String body=cursor.getString(cursor.getColumnIndex(DiaryDao.Properties.Body.columnName));
                        String date=cursor.getString(cursor.getColumnIndex(DiaryDao.Properties.Date.columnName));
                        shareText("Share to?","title:"+title+"\ncontent:"+body+"\n\ndate:"+date);
                        break;
                    case 1:
                        cursor.moveToPosition(position);
                        long id=cursor.getLong(cursor.getColumnIndex(DiaryDao.Properties.Id.columnName));
                        DiaryDao.deleteByKey(id);
                        cursor.requery();
                        Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                        break;
                }
                return false;
            }
        });
    }
    //初始化DAO
    private void InitDAO() {
        DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db",
                null);
        db = helper.getWritableDatabase();
        daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
        diaryDao = daoSession.getDiaryDao();
    }

    //初始化ListView
    private void InitList() {
        String textColumn = DiaryDao.Properties.Title.columnName;
        String dateColumn = DiaryDao.Properties.Date.columnName;
        String bodyColumn=DiaryDao.Properties.Body.columnName;
        String orderBy = dateColumn + " COLLATE LOCALIZED DESC";
        cursor = db.query(diaryDao.getTablename(), diaryDao.getAllColumns(),
                null, null, null, null, orderBy);
        String[] from = { textColumn,bodyColumn,dateColumn };
        int[] to = { R.id.text1, R.id.body,R.id.date };
        adapter = new SimpleCursorAdapter(this,
                R.layout.diary_row, cursor, from, to);
        listView.setAdapter(adapter);
    }

    // 添加选择菜单
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu,menu);

        //添加SearchView控件
        MenuItem searchItem=menu.findItem(R.id.search);
        search=(SearchView) MenuItemCompat.getActionView(searchItem);
        search.setQueryHint("title、etc.");
        search.setSubmitButtonEnabled(true);
        search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                search.clearFocus();  //可以收起键盘
                search.onActionViewCollapsed();    //可以收起SearchView视图
                search_Text(query);
                search_comfirm="true";
                return true;
            }
            @Override
            public boolean onQueryTextChange(String newText) {
                if(newText.equals("")){
                    flag=0;
                    listView.setAdapter(adapter);
                }
                search_Text(newText);
                return false;
            }
        });
        super.onCreateOptionsMenu(menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        }
        return super.onOptionsItemSelected(item);
    }

    private void search_Text(String newtitle){
        String textColumn = DiaryDao.Properties.Title.columnName;
        String dateColumn = DiaryDao.Properties.Date.columnName;
        String bodyColumn=DiaryDao.Properties.Body.columnName;
        cursor1 = db.query(diaryDao.getTablename(), diaryDao.getAllColumns(),
                "TITLE like ?", new String[]{"%"+newtitle+"%"},null, null, null);
        String[] from = { textColumn,bodyColumn,dateColumn };
        int[] to = { R.id.text1, R.id.body,R.id.date };
        adapter = new SimpleCursorAdapter(this,
                R.layout.diary_row, cursor1, from, to);
        //setListAdapter(adapter);
        listView.setAdapter(adapter);
    }

    private long firstPressedTime;
    // System.currentTimeMillis() 当前系统的时间
    @Override
    public void onBackPressed() {
        if(search_comfirm.equals("false")) {
            if (flag == 1) {
                if (System.currentTimeMillis() - firstPressedTime < 2000) {
                    super.onBackPressed();
                } else {
                    Toast.makeText(MainActivity.this, "再按一次退出", Toast.LENGTH_SHORT).show();
                    firstPressedTime = System.currentTimeMillis();
                }
            } else {
                search.onActionViewCollapsed();    //可以收起SearchView视图
                flag = 1;
            }
        }
        else{
            search_comfirm="false";
            Intent intent=new Intent(this,MainActivity.class);
            startActivity(intent);
            finish();
        }
    }

    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {
        cursor.requery();
        super.onActivityResult(requestCode, resultCode, intent);
    }


    //分享
    private void shareText(String dlgTitle,String content) {
        if (content == null || "".equals(content)) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, content);
        // 设置弹出框标题
        if (dlgTitle != null && !"".equals(dlgTitle)) { // 自定义标题
            startActivity(Intent.createChooser(intent, dlgTitle));
        } else { // 系统默认标题
            startActivity(intent);
        }
    }
}
